package com.guet.service.impl;

import com.guet.DTO.RegisterDTO;
import com.guet.Entity.User;
import com.guet.constant.UserConstant;
import com.guet.exception.AccountDuplicate;
import com.guet.exception.PasswordErrorException;
import com.guet.mapper.RegisterMapper;
import com.guet.service.RegisterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

@Service
public class RegisterServiceImpl implements RegisterService {
    @Autowired
    private RegisterMapper registerMapper;
    @Override
    public void register(RegisterDTO registerDTO) {
        // 先查账号是否冲突
        if (registerMapper.queryAccount(registerDTO.getAccount())) {
            throw new AccountDuplicate("账号已存在");
        }
        if(!registerDTO.getPassword().equals(registerDTO.getConfirmPassword())){
            throw new PasswordErrorException("两次输入的密码不一致");
        }
        String password = registerDTO.getPassword();
        if (!password.matches("^(?=.*[A-Za-z])(?=.*\\d)[A-Za-z\\d]{8,20}$")){
            throw new PasswordErrorException("密码必须为8到20位，且包含字母和数字");
        }
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        User user = User.builder()
                .account(registerDTO.getAccount())
                .password(password)
                .identify(registerDTO.getIdentify())
                .status(UserConstant.USER_ENABLED)
                .avatar(UserConstant.DEFAULT_AVATAR)
                .build();
        registerMapper.register(user);
    }
}

